package rahmath.sharif.docrypt.util;

import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.BinaryCodec;
import org.apache.commons.codec.binary.Hex;

import rahmath.sharif.docrypt.constant.EncodingType;

public class BaseCoder {

	private static String UTF8 = "UTF-8";
	private static final BinaryCodec binaryCodec = new BinaryCodec();
	private static final Hex hex = new Hex();
	private static final Base32 base32 = new Base32();
	private static final Base64 base64 = new Base64();

	public static String encodeToString(EncodingType encodingType, String string) {
		try {
			return encodeToString(encodingType, string.getBytes(UTF8));
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String decodeToString(EncodingType encodingType, String string) {
		try {
			return new String(decodeToBytes(encodingType, string), UTF8);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String encodeToString(EncodingType encodingType,
			byte[] byteArray) {
		try {
			switch (encodingType) {
			case BASE2:
				return new String(binaryCodec.encode(byteArray), UTF8);
			case BASE8:
				return Base8.encode(byteArray);
			case BASE16:
				return new String(hex.encode(byteArray), UTF8);
			case BASE32:
				return new String(base32.encode(byteArray), UTF8);
			case BASE64:
				return new String(base64.encode(byteArray), UTF8);
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static byte[] decodeToBytes(EncodingType encodingType, String string) {
		try {
			switch (encodingType) {
			case BASE2:
				return binaryCodec.decode(string.getBytes(UTF8));
			case BASE8:
				return Base8.decode(string);
			case BASE16:
				return hex.decode(string.getBytes(UTF8));
			case BASE32:
				return base32.decode(string.getBytes(UTF8));
			case BASE64:
				return base64.decode(string.getBytes(UTF8));
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
